<?php

use ChatX\Mqtt\MqttPHP;

require __DIR__ . '/../vendor/autoload.php';
try {
    $client_id = 'php-subscribe-' . uniqid(); // make sure this is unique for connecting to sever - you could use uniqid()

    $mqtt = new MqttPHP('8.155.41.188', '1883', $client_id);
    $mqtt->connect(true, null, null, null);
    echo "Connected to MQTT broker\n";
    // 定义消息处理回调函数
    $callback = function($topic, $message) {
        echo "Received message on topic 【{$topic}】 Message: 【{$message}】\n";
    };

    // 将回调函数添加到订阅主题配置中
    $topics['test/topic'] = ["qos" => 0, "function" => $callback];
    $success = $mqtt->subscribe($topics, 0);


    if ($success) {
        echo "Subscribed to topics: " . implode(', ', array_keys($topics)) . "\n";
        echo "Waiting for messages... (Press Ctrl+C to exit)\n";
        // Keep listening for messages
        while ($mqtt->proc()) {
            // 可以在这里添加一些延迟逻辑，减少CPU占用
            usleep(100000);
        }
    } else {
        echo "Failed to subscribe to topics\n";
    }
    $mqtt->close();
    echo "Disconnected from MQTT broker\n";
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
}

